import { ref } from "vue";
import { http } from "../http";
import { Book } from "../interface/book.interface";

export function useBook() {
  const book = ref({} as Book);

  async function getBook(id: string) {
    book.value = (await http.get(`/books/${id}`)).data;
  }

  async function updateBookNum(id: string, number: number) {
    await http.patch(`/books/${id}`, {
      number,
    });
  }

  return {
    book,
    getBook,
    updateBookNum,
  };
}

export function useBooks() {
  const books = ref([] as Book[]);

  async function getAllBooks(
    bookName: string = "",
    page: number = 1,
    pageSize: number = 20
  ): Promise<number> {
    const res = (
      await http.get(`/books`, {
        params: {
          like: bookName,
          page,
          pageSize,
        },
      })
    ).data;
    books.value = res.items;
    return res.total;
  }

  async function getBooks(id: string) {
    books.value = (await http.get(`/books/category/${id}`)).data;
  }

  return {
    books,
    getAllBooks,
    getBooks,
  };
}
